from flask import Flask, Response, redirect, url_for, abort, make_response, json, jsonify

app = Flask(__name__)


@app.route('/')
def index():
    return "<h1>Response Testing</h1>"


@app.route('/hello')
def hello():
    return '<h1>Hello</h1>', 201


# 直接硬编码实现重定向
@app.route('/red_hardcode')
def redirect01():
    return '', 301, {'Location': 'https://www.baidu.com'}


# 使用redirect函数
@app.route('/red_func')
def redirect02():
    return redirect('https://www.baidu.com')


# 使用redirect函数和url_for函数
@app.route('/red_url_for')
def redirect03():
    return redirect(url_for('index'))


# 返回404
@app.route('/404')
def not_found():
    abort(404)


# 生成其他MIME类型的响应
@app.route('/make_resp')
@app.route('/make_resp/<int:type>')
def make_resp(type=0):
    resp = make_response('<root>create response!</root>')
    if type==1: # text
        resp.mimetype = 'text/plain'
    elif type==2: # xml
        resp.mimetype = 'application/xml'
    elif type==3: # json
        data = {
            'name': 'XiaoLei',
            'gender': 'Male'
        }
        resp = make_response(json.dumps(data))
        resp.mimetype = 'application/json'
    elif type==4: # 快捷json
        resp = jsonify(name='xiao', gender='男')
    return resp
